<template>
  <div
    :class="animate"
    :style="{ height: height, width: width }"
    :id="chartOption.bindingDiv"
    ref="text"
  >
    <div :style="normalTextStyle" ref="noticeInner">
      <div :style="textWidth">
        {{ lampMsg }}
      </div>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";

import "../../animate/animate.css";
import { getFormsource } from "@/api/tool/datav/formsource";
import { parseQueryString, fIsUrL } from "../../util/urlUtil";
import { chartApiBar,chartBIanalysis } from "@/api/tool/datav/chartApi";
import { websocketCommand } from "../../util/websocket.js";

const animationDuration = 6000;

export default {
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object
    }
  },
  data() {
    return {
      chart: null,
      dataOption: JSON.parse(JSON.stringify(this.chartOption)),
      textArr: [],
      lampMsg: "",
      timer: "",
      loopTimer:"",
      sObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
    };
  },
  watch: {
    width() {},
    height() {},
    chartOption: {
      deep: true,
      handler(newVal) {
        this.setOptions(JSON.parse(JSON.stringify(newVal)));
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
    clearTimeout(this.timer);
    clearTimeout(this.loopTimer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  computed: {
    normalTextStyle() {
      const style = {
        color: this.chartOption.fontColor,
        fontSize: this.chartOption.fontSize + "px",
        fontFamily: this.chartOption.fontFamily,
        lineHeight: this.chartOption.lineHeight + "px",
        backgroundColor: this.chartOption.backgroundColor,
        height: this.height,
        width: this.width,
        fontWeight: this.chartOption.fontWeight,
        letterSpacing: this.chartOption.letterSpacing + "px",
        textAlign: this.chartOption.textAlign,
        overflow: "hidden"
      };
      return style;
    },

    text() {
      const arr = this.chartOption.staticDataValue.split("|");
      return arr;
    }
  },
  methods: {
    initChart() {
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (this.loopTimer != "") {
        clearTimeout(this.loopTimer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
           
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    textWidth() {
      let lampWidth =
        this.lampMsg.length * parseInt(this.chartOption.fontSize) + 5;

      const style = { position: "absolute", width: lampWidth + "px" };
      return style;
    },
    setOptions: async function(dataOption) {
      //初始化数据
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url" || dataOption.isStaticData == false) {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;

        let result = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
        dataOption.staticDataValue = result;
      } else if (dataOption.dataSourceType == "database") {
        if (dataOption.database.executeSql != undefined && dataOption.database.executeSql != '') {
          
          let result = [];
          if(dataOption.database.sqlType == 'custom'){
          
            result = await chartBIanalysis(dataOption.database);
          }
          if (result.code == 200) {
            dataOption.staticDataValue = result.data;
            //console.log(dataOption.staticDataValue);
          } else {
            alert("操作数据库错误");
          }
        }
      } else if (dataOption.dataSourceType == "form") {
        if (dataOption.formSource != undefined) {
          let response = await getFormsource(dataOption.formSource.id);
          dataOption.staticDataValue = JSON.parse(response.data.formData);
        }
      }else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;
          }
        }
      }


      if (this.loopTimer != "") {
        clearTimeout(this.loopTimer);
      }

      if(dataOption.newDataFormat == true || typeof dataOption.staticDataValue != 'string'){
           
        dataOption.staticDataValue = dataOption.staticDataValue[0].text;
        
      }

        //数据处理
       if(dataOption.customData != undefined && dataOption.customData != ""){
        
        try {
          dataOption.staticDataValue = (
          
            //里面为要处理的代码块
          eval(dataOption.customData) 
          
          )(
            dataOption.staticDataValue,
            this.$refs.text
          );
        } catch (error) {
          console.log(error)
        }
        
       }

        //交互组件配置
      if(dataOption.interactData != undefined && dataOption.interactData != ""){
          try {
              dataOption.staticDataValue = (        
              //里面为要处理的代码块
              eval(dataOption.interactData)             
            )(
              dataOption.staticDataValue,
              this.$refs.text
            );
          } catch (error) {
            console.log(error)
          }               
       }  

      this.init(dataOption);
    },
    init(data) {
      let currentIndex = 0;
      const arr = data.staticDataValue.split("|");
      //this.lampMsg = arr[currentIndex];

      let boxWidth = this.$refs.text.offsetWidth;
      let innerWidth = 0;
      let child = this.$refs.noticeInner.childNodes;

      let padding = 0;

      let animation = () => {
        padding -= 1;
        let lampWidth =
          (arr[currentIndex].length + data.letterSpacing) *
            parseInt(data.fontSize) +
          5;
        this.lampMsg = arr[currentIndex];
        this.$refs.noticeInner.childNodes[0].style.cssText =
          "position:'absolute';width:" +
          lampWidth +
          "px;transform: translate3d(" +
          padding +
          "px, 0, 0)";
        //console.log((innerWidth - parseInt(window.getComputedStyle(child[0]).width.split('px')[0])));
        //console.log(padding);
        if (
          padding ===
          innerWidth -
            parseInt(window.getComputedStyle(child[0]).width.split("px")[0])
        ) {
          padding = this.width.split("px")[0];
          this.$refs.noticeInner.childNodes[0].style.cssText =
            "position:'absolute';width:" +
            lampWidth +
            "px;transform: translate3d(" +
            padding +
            "px, 0, 0)";
          if (currentIndex < arr.length - 1) {
            currentIndex++;
          } else {
            currentIndex = 0;
          }
        }
        this.loopTimer = setTimeout(function() {
          animation();
        }, data.loopDelay);
      };

      animation();
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = e.result;
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }
  }
};
</script>
